<template>
	<view class="content">
		<view class="row b-b">
			<text class="tit">联系人</text>
			<input class="input" type="text" v-model="addressData.name" placeholder="收货人姓名" placeholder-class="placeholder" />
		</view>
		<view class="row b-b">
			<text class="tit">手机号</text>
			<input class="input" type="number" v-model="addressData.mobile" placeholder="收货人手机号码" placeholder-class="placeholder" />
		</view>
		<view class="row b-b">
			<text class="tit">地址</text>
			<text @click="chooseLocation" class="input" :class="{'placeholder': (!addressData.addressName2 && !addressData.addressName) || displayAddress() === '在地图选择'}">
				{{displayAddress()}}
			</text>
			<text class="yticon icon-shouhuodizhi"></text>
		</view>
		<view class="row b-b"> 
			<text class="tit">门牌号</text>
			<input class="input" type="text" v-model="addressData.addr" placeholder="楼号、门牌" placeholder-class="placeholder" />
		</view>
		
		<view class="row default-row">
			<text class="tit">设为默认</text>
			<switch :checked="addressData.default" color="#fa436a" @change="switchChange" />
		</view>
		<button class="add-btn" @click="confirm">提交</button>
	</view>
</template>

<script>
import api from '@/utils/api'
	export default {
		data() {
		    return {
		        addressData: {
		            name: '',
		            mobile: '',
		            address: '',
		            addressName: '',
		            addressName2: '',
		            area: '',
		            default: false,
		            lng: '',
		            lat: ''
		        },
		        manageType: 'add',
		    };
		},
		onLoad(option){
			let title = '新增收货地址';
			if(option.type==='edit'){
				title = '编辑收货地址'
				const incoming = JSON.parse(option.data)
				this.addressData = incoming
				// 优先使用列表中的 addressName2 作为显示
				this.addressData.addressName2 = incoming.addressName2 || ''
				// 回填门牌/详细地址（detail 优先，其次 addr）
				this.addressData.addr = incoming.detail || incoming.addr || ''
			}
			this.manageType = option.type;
			uni.setNavigationBarTitle({
				title
			})
		},
		methods: {
			// 计算展示用地址：优先 addressName2，其次 addressName，最后提示
			displayAddress(){
				const name2 = this.addressData && this.addressData.addressName2
				const name1 = this.addressData && this.addressData.addressName
				return name2 || name1 || '在地图选择'
			},
			switchChange(e){
				this.addressData.default = e.detail && e.detail.value;
			},
			
			//地图选择地址
			chooseLocation(){
				console.log('开始选择位置...');
				// #ifdef H5
				uni.navigateTo({
					url: '/pages/address/addressH5Picker',
					success: (res) => {
						const channel = res.eventChannel;
						channel.on('h5LocationPicked', (data) => {
							if (!data) return;
							this.addressData.addressName = data.name || '已选择位置';
							this.addressData.address = data.address || data.name;
						// 为了让 displayAddress() 显示最新选择，清空/重设 addressName2
						this.addressData.addressName2 = `${data.province || ''}${data.city || ''}${data.area || ''}`;
							this.addressData.lng = data.lng;
							this.addressData.lat = data.lat;
						// 同步省市区
						this.addressData.province = data.province || '';
						this.addressData.city = data.city || '';
						this.addressData.area = data.area || '';
						// 拓展字段：街道、门牌、乡镇、行政编码
						this.addressData.street = data.street || '';
						this.addressData.streetNumber = data.streetNumber || '';
						this.addressData.town = data.town || '';
						this.addressData.adcode = data.adcode || '';
						// 若未填写门牌号，尝试用街道+门牌号预填到 addr
						if(!this.addressData.addr){
							const streetLine = `${this.addressData.street || ''}${this.addressData.streetNumber || ''}`;
							if (streetLine) this.addressData.addr = streetLine;
						}
							this.$api && this.$api.msg ? this.$api.msg('地址选择成功') : uni.showToast({ title: '选择成功', icon: 'none' });
						});
					}
				});
				return;
				// #endif
				// 直接尝试选择位置，让系统处理权限问题
				this.startLocationChoose();
			},
			
			// 开始位置选择
			startLocationChoose(){
				console.log('开始选择位置...');
				// 检查uni.chooseLocation是否可用
				if (typeof uni.chooseLocation !== 'function') {
					console.error('uni.chooseLocation 不可用');
					this.$api.msg('当前环境不支持地图选择功能');
					return;
				}
				
				uni.chooseLocation({
					success: (data)=> {
						console.log('地图选择成功:', data);
						this.addressData.addressName = data.name || '已选择位置';
						this.addressData.address = data.address || data.name;
					this.addressData.addressName2 = '';
						// 保存经纬度信息，用于后续使用
						this.addressData.lng = data.longitude;
						this.addressData.lat = data.latitude;
						this.$api.msg('地址选择成功');
					},
					fail: (err) => {
						console.error('地图选择失败:', err);
						let errorMsg = '地图选择失败';
						
						// 根据错误类型给出具体提示
						if (err && err.errMsg) {
							console.log('错误详情:', err.errMsg);
							if (err.errMsg.includes('cancel')) {
								errorMsg = '用户取消选择';
							} else if (err.errMsg.includes('auth') || err.errMsg.includes('permission')) {
								errorMsg = '定位权限被拒绝，请在设置中开启';
							} else if (err.errMsg.includes('network')) {
								errorMsg = '网络错误，请检查网络连接';
							} else if (err.errMsg.includes('not support')) {
								errorMsg = '当前环境不支持地图选择';
							} else {
								errorMsg = `选择失败: ${err.errMsg}`;
							}
						} else {
							console.log('未知错误:', err);
							errorMsg = '地图选择失败，请重试';
						}
						
						this.$api.msg(errorMsg);
						
						// 如果是权限问题，引导用户去设置
						if (err && err.errMsg && (err.errMsg.includes('auth') || err.errMsg.includes('permission'))) {
							setTimeout(() => {
								uni.showModal({
									title: '需要定位权限',
									content: '请在设置中开启定位权限后重试',
									confirmText: '去设置',
									success: (res) => {
										if (res.confirm) {
											if (typeof uni.openSetting === 'function') {
												uni.openSetting();
											} else {
												this.$api.msg('请手动在设置中开启定位权限');
											}
										}
									}
								});
							}, 1000);
						}
					}
				});
			},
			
			//提交
			confirm(){
				let data = this.addressData;
				if(!data.name){
					this.$api.msg('请填写收货人姓名');
					return;
				}
				if(!/^1[3-9][0-9]{9}$/.test(data.mobile)){
					this.$api.msg('请输入正确的手机号码');
					return;
				}
				if(!data.address){
					this.$api.msg('请在地图选择所在位置');
					return;
				}
				// 提交前若省市区为空且有addressName，尝试从addressName拆分（兜底）
				if((!data.province || !data.city || !data.area) && data.addressName){
					// 简单拆分：按常见的 省/市/区 顺序截取（如果是直辖市/自治区可能需后端兜底）
					const m = data.addressName.match(/^(.*?省|北京|天津|上海|重庆|新疆维吾尔自治区|广西壮族自治区|内蒙古自治区|宁夏回族自治区|西藏自治区)?(.*?市)?(.*?[区县])/);
					if(m){
						this.addressData.province = this.addressData.province || (m[1] || '');
						this.addressData.city = this.addressData.city || (m[2] || '');
						this.addressData.area = this.addressData.area || (m[3] || '');
					}
				}
				if(!data.addr){
					this.$api.msg('请填写门牌号信息');
					return;
				}
				// 映射到后端实体字段
				const payload = {
					addrId: data.addrId || undefined,
					userId: data.userId || undefined,
					mobile: data.mobile,
					isDefault: data.default ? 1 : 0,
					consignee: data.name,
					provinceId: data.provinceId || undefined,
					province: data.province || '',
					cityId: data.cityId || undefined,
					city: data.city || '',
					areaId: data.areaId || undefined,
					area: data.area || '',
					postCode: data.postCode || '',
					addr: data.addr,
					lng: data.lng ? Number(data.lng) : undefined,
					lat: data.lat ? Number(data.lat) : undefined
				}
				const isEdit = this.manageType === 'edit' && payload.addrId
				const req = isEdit ? api.updateAddress(payload) : api.addAddress(payload)
				req.then((res)=>{
					// 成功后刷新上一页列表
					this.$api.prePage().refreshList(payload, this.manageType);
					this.$api.msg(`地址${isEdit ? '修改': '添加'}成功`);
					setTimeout(()=>{ uni.navigateBack() }, 800)
				}).catch(()=>{})
			},
		}
	}
</script>

<style lang="scss">
	page{
		background: $page-color-base;
		padding-top: 16upx;
	}


	.row{
		display: flex;
		align-items: center;
		position: relative;
		padding:0 30upx;
		height: 110upx;
		background: #fff;
		
		.tit{
			flex-shrink: 0;
			width: 120upx;
			font-size: 30upx;
			color: $font-color-dark;
		}
		.input{
			flex: 1;
			font-size: 30upx;
			color: $font-color-dark;
			
			&.placeholder{
				color: $font-color-light;
			}
		}
		.icon-shouhuodizhi{
			font-size: 36upx;
			color: $font-color-light;
		}
	}
	.default-row{
		margin-top: 16upx;
		.tit{
			flex: 1;
		}
		switch{
			transform: translateX(16upx) scale(.9);
		}
	}
	.add-btn{
		display: flex;
		align-items: center;
		justify-content: center;
		width: 690upx;
		height: 80upx;
		margin: 60upx auto;
		font-size: $font-lg;
		color: #fff;
		background-color: $base-color;
		border-radius: 10upx;
		box-shadow: 1px 2px 5px rgba(219, 63, 96, 0.4);
	}
	.map-container {
		margin: 16upx 0;
		padding: 20upx 30upx;
		background: #fff;
		
		.map-title {
			font-size: 30upx;
			color: $font-color-dark;
			margin-bottom: 10upx;
		}
		
		.map-tip {
			font-size: 26upx;
			color: $font-color-light;
		}
	}
</style>
